# -*- coding: utf8 -*-
import logging
import re
import common
from BeautifulSoup import BeautifulSoup

site_index = 'kget'
site_keyword = 'kget'
site_url = 'http://www2.kget.jp/releasedate/'
test_url = 'http://lyric.kget.jp/lyric/pt/jw/index.html'

def get_lyric(url):
    # get lyric page first
    data = common.get_url_content(url)

    prefix = 'http://lyric.kget.jp/iframe/sendlyric.aspx?sn='
    pattern = 'lyric.swf\?sn=([a-zA-Z0-9\/]+)'

    bool = re.compile(pattern).search(data)

    if bool:
        id = bool.group(1)
        full_url = prefix + id
        
        # get data
        data = common.get_url_content(full_url)

        lyric = unicode(data, 'sjis')
        front_str = 'lyric='
        start = lyric.find(front_str) + len(front_str)
        lyric = lyric[start:]
        lyric = lyric.strip()

        # test for half to full
        lyric = common.half2full(lyric)

        song_info = _get_song_info(url)
        lyric = song_info + lyric

        return lyric.strip()


    return None

def _get_song_info(url):
    data = common.get_url_content(url)

    encoding = 'sjis'
    data = data.decode(encoding, 'ignore')

    soup = BeautifulSoup(data)

    lines = []

    # title
    pattern = '<h2><a [^>]+>(.*)</a></h2>'
    bool = re.compile(pattern).search(data)
    if bool:
        title = bool.group(1)
        logging.debug('title: %s' % (title))
    else:
        title = ''

    # artist, lyric, music
    div = soup.find('div', {'class': 'pane lyricinfo'})
    trs = [unicode(x) for x in div.findAll('tr')] 
    tmp = '\n'.join((trs))
    info = re.sub(r'<[^>]+>', '', tmp)

    lines.append(u'%s\n' % (title))
    lines.append(info)

    lines.append('\n\n')

    string = '\n'.join(lines)

    return string

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    url = test_url
    print url
    lyric = get_lyric(url)
    print repr(lyric) 
